// pages/device/active/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), common_Js = require("../../../component/common.js")
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        device:{},
        device_id:0,
        name:'',
        phone_num:'',
        card_num:'',
        submitState:false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.id){
            this.data.device_id = parseInt(options.id);
        }
        this.onHttpInit()
    },

  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    console.log('onHttpInit')
    var that = this;
    fetchApi.httpPost('/device/welding/detail', {
      device_id:that.data.device_id,
    }, function (res) {
      console.log("传感器设备响应数据", res)
      if (res.data.code == 0) {
        that.setData({
            device: res.data.data.device
        })
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  bindInput(e){
      var key = e.currentTarget.dataset.key;
      if(key == 'name'){
        this.data.name = e.detail || "";
      } else if(key == 'phone'){
        this.data.phone_num = e.detail || "";
      } else if(key == 'card_num'){
        this.data.card_num = e.detail || "";
      }
  },
  
  /**
   * 获取页面数据的 http请求
   */
  onHttpSubmit: function () {
    var that = this;
    if(this.data.name == ''){
        Toast.fail('姓名不能为空');
        return;
    }
    if(this.data.phone_num == ''){
        Toast.fail('手机号不能为空');
        return;
    }
      if(this.data.card_num == ''){
          Toast.fail('电焊证书编号不能为空');
          return;
      }
      if(this.data.card_num.length != 19){
          Toast.fail('请输入正确的证书编号');
          return;
      }
    fetchApi.httpPost('/device/welding/active', {
        device_id:that.data.device_id,
        name:that.data.name,
        phone:that.data.phone_num,
        certificate:that.data.card_num,
    }, function (res) {
      console.log("设备激活响应数据", res)
      if (res.data.code == 0) {
          Toast.success(res.data.msg);
        setTimeout(function(){
            wx.redirectTo({ url: '/pages/welding/use/index?id=' + that.data.device_id})
        },500);
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
})